package cn.ijero.pictureselector.delegate;

import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import cn.ijero.pictureselector.R;
import cn.ijero.pictureselector.data.GroupLocalMedia;
import cn.ijero.pictureselector.data.LocalMedia;
import cn.ijero.pictureselector.loader.image.ImageLoader;
import cn.ijero.pictureselector.util.MimeTypeUtil;

public class PictureSelectorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final ArrayList<GroupLocalMedia> checked = new ArrayList<>();
    private onItemCheckedChangedListener listener;

    private static final String TAG = "PictureSelectorAdapter";
    private final List<GroupLocalMedia> data = new ArrayList<>();
    private int targetSize = 0;

    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;

    public PictureSelectorAdapter() {
        DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
        // 缩略图大小=设备宽度/4
        targetSize = displayMetrics.widthPixels / 4;
    }

    @Override
    public int getItemViewType(int position) {
        GroupLocalMedia localMedia = data.get(position);
        boolean header = localMedia.isHeader();
        if (header) {
            return TYPE_HEADER;
        }
        return TYPE_ITEM;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER) {
            return new HeaderViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_header, parent, false));
        }
        return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_picture, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        int adapterPosition = holder.getAdapterPosition();
        int viewType = holder.getItemViewType();
        GroupLocalMedia groupLocalMedia = data.get(adapterPosition);
        LocalMedia item = groupLocalMedia.getLocalMedia();

        if (viewType == TYPE_HEADER) {
            HeaderViewHolder viewHolder = (HeaderViewHolder) holder;
            viewHolder.textView.setText(data.get(adapterPosition).getGroup());
            viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    String group = groupLocalMedia.getGroup();
                    ArrayList<GroupLocalMedia> localMedias = new ArrayList<>();
                    for (GroupLocalMedia media : data) {
                        if (media.getGroup().equals(group) && !media.isHeader()) {
                            localMedias.add(media);
                        }
                    }
                    if (isChecked) {
                        check(localMedias);
                    } else {
                        uncheck(localMedias);
                    }
                }
            });
            return;
        }
        ItemViewHolder viewHolder = (ItemViewHolder) holder;
        long start = System.currentTimeMillis();
        long end = System.currentTimeMillis() - start;
        Log.d(TAG, "readAndResizeBitmap: 解析耗时 " + end + " ms");

        ImageView imageView = viewHolder.imageView;

        int visibility = View.GONE;
        String location = "";
        if (item.hasLocation()) {
            visibility = View.VISIBLE;
            location = item.getLatitude() + ";" + item.getLongitude();
            viewHolder.locationTextView.setText(location);
        }
        viewHolder.locationImageView.setVisibility(visibility);
        viewHolder.locationTextView.setVisibility(visibility);


        boolean video = MimeTypeUtil.isVideo(item.getMimeType());
        int videoVisibility = View.GONE;
        if (video) {
            videoVisibility = View.VISIBLE;
        }
        viewHolder.videoImageView.setVisibility(videoVisibility);

        int checkedVisibility = View.GONE;
        if (checked.contains(data.get(adapterPosition))) {
            checkedVisibility = View.VISIBLE;
        }
        viewHolder.checkImageView.setVisibility(checkedVisibility);

        ImageLoader.get()
                .load(item.getData(), item.getMimeType())
                .overrideSize(targetSize)
                .placeHolder(R.drawable.ic_loading)
                .into(imageView);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle(adapterPosition);
                if (listener != null) {
                    listener.onCheckChanged();
                }
            }
        });
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            this.onBindViewHolder(holder, position);
            return;
        }
        ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
        int adapterPosition = itemViewHolder.getAdapterPosition();
        int visibility = View.GONE;
        if (checked.contains(data.get(adapterPosition))) {
            visibility = View.VISIBLE;
        }
        itemViewHolder.checkImageView.setVisibility(visibility);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    private void check(ArrayList<GroupLocalMedia> checked) {
        int startIndex = getCheckStartIndex(checked, true);
        notifyItemRangeChanged(startIndex, checked.size(), true);
        if (listener != null) {
            listener.onCheckChanged();
        }
    }

    private void uncheck(ArrayList<GroupLocalMedia> checked) {
        int startIndex = getCheckStartIndex(checked, false);
        notifyItemRangeChanged(startIndex, checked.size(), false);
        if (listener != null) {
            listener.onCheckChanged();
        }
    }

    private int getCheckStartIndex(ArrayList<GroupLocalMedia> checked, boolean isChecked) {
        ArrayList<GroupLocalMedia> tempChecked = new ArrayList<>();
        for (GroupLocalMedia localMedia : checked) {
            if (isChecked) {
                if (!this.checked.contains(localMedia)) {
                    tempChecked.add(localMedia);
                }
            } else {
                if (this.checked.contains(localMedia)) {
                    tempChecked.add(localMedia);
                }
            }
        }
        if (isChecked) {
            this.checked.addAll(tempChecked);
        } else {
            this.checked.removeAll(tempChecked);
        }
        GroupLocalMedia willCheckedFirst = checked.get(0);
        return this.data.indexOf(willCheckedFirst);
    }

    private void toggle(int position) {
        GroupLocalMedia localMedia = data.get(position);
        if (checked.contains(localMedia)) {
            checked.remove(localMedia);
        } else {
            checked.add(localMedia);
        }
        notifyItemChanged(position, checked.contains(localMedia));
    }

    public void setData(List<GroupLocalMedia> data) {
        this.data.clear();
        this.data.addAll(data);
        notifyItemRangeChanged(0, data.size());
    }

    public List<GroupLocalMedia> getData() {
        return data;
    }

    public List<GroupLocalMedia> getChecked() {
        return checked;
    }

    public void setOnItemCheckedChangeListener(onItemCheckedChangedListener listener) {
        this.listener = listener;
    }

    static class HeaderViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        CheckBox checkbox;

        public HeaderViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.text_view);
            checkbox = itemView.findViewById(R.id.checkbox);
        }
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        ImageView imageView;
        ImageView checkImageView;
        ImageView videoImageView;
        View locationImageView;
        TextView locationTextView;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view);
            videoImageView = itemView.findViewById(R.id.video_image_view);
            locationImageView = itemView.findViewById(R.id.location_shadow_view);
            locationTextView = itemView.findViewById(R.id.location_text_view);
            checkImageView = itemView.findViewById(R.id.check_image_view);
        }

    }


    /**
     * 条目的多选变化监听器
     */
    public interface onItemCheckedChangedListener {
        void onCheckChanged();
    }

}
